﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Luna.Extender;
using System.Xml;
using System.Reflection;

namespace Luna.Framework.Extender
{
	public class XmlExtensionItem : IExtensionItem
	{
		private XmlNode node;
		private IList<IExtensionItem> children;

		internal XmlExtensionItem(XmlExtensionManager manager, XmlNode node) {
			this.node = node;
			ExtentionManager = manager;

			children = new List<IExtensionItem>();

			foreach (XmlNode child in node.ChildNodes) {
				IExtensionItem c = manager.createExtentionItem(child);
				if (c != null)
					children.Add(c);
			}
		}

		protected XmlExtensionManager ExtentionManager { get; private set; }

		#region IExtensionItem Members

		public string Name {
			get {
				return node.Name;
			}
			set {
				
			}
		}

		public virtual string this[string propertyName] {
			get {
				return node.getAttribute(propertyName);
			}
			set {
				node.setAttribute(propertyName, value);
			}
		}

		public IList<IExtensionItem> Children {
			get { return children; }
		}

		public virtual Type Type {
			get {
				return string.IsNullOrEmpty((string)this["class"]) ? null : 
						Type.GetType((string)this["class"], false, true);
			}
			set {
				this["class"] = value.FullName;
			}
		}

		public virtual object createExtension(IAppContext context) {
			return this.createExtensionFromItem(context);
		}
		#endregion

		#region IPropertyProvider Members

		public virtual TPropType getProperty<TPropType>(object key) {
			IExtensionItem child = Children.FirstOrDefault(c => c["Name"].Equals(key.ToString()));
			if (child != null)
				return child["Value"].convertTo<TPropType>();
			return default(TPropType);
		}

		public virtual void setProperty<TPropType>(object key, TPropType value) {
			// Do nothing
		}

		#endregion
	}
}
